// 数据交互
/* 
    不可以直接进入详情页，会出现一个问题，地址栏没有传参，就不知道显示的到底是哪个商品的id，也就是哪个商品的详情信息
    详情页之数据渲染：
          1.获取地址栏中的信息，并判断是否有参数
          2.当地址栏中存在参数时，才可以正确进入
          3.把参数id获取到以后，再通过自执行函数获取数据库中该id所对应的数据
          4.渲染到页面中
*/
// 获取操作对象
var xiangqing1 = document.querySelector("#xiangqing1");
// 获取地址栏中的信息
var search1 = location.search;
var data = "";
// 判断地址栏中是否存在参数
if (search1) {
  // console.log(search1); //?id=4
  // 将获取到的进行分割，目的是拿到4
  // 然后将id=4拿到数据库中进行查询
  var id1 = search1.split("=")[1];
  // console.log(id1); //4
  (async function () {
    // 获取响应结果
    data = await PromiseAjax({
      url: "../php/xiangqing.php",
      data: "id=" + id1,
    });
    // console.log(data);
    // 把接收到的数据转为json对象
    data = eval("(" + data + ")");
    // console.log(data);
    // 给当前商品设置详情信息
    var str = `
    <div class="enlarge fl">
    <div class="middle">
        <img src="${data.goods_small_logo}" alt="" style='width:350px;height:350px;'>
        <div class="shade"></div>
        <div class="big" style='background:"url(${data.goods_big_logo}) no-repeat";'></div>
    </div>
    <div class="small">
        <img src="../images/zuojiantou.png" alt="" >
        <img class="active" src="${data.goods_small_logo}" alt="" style='width:51px;height:51px;'>
        
        <img src="../images/youjiantou.png" alt="">
    </div>
</div>
<div class="fangda-right fl">
    <p>${data.goods_name}</p>
    <div class="prive-quan">
        <p class="price"><i style="color: #666;">京东价&nbsp;&nbsp;&nbsp;</i><span style="color: red;">￥<span>${data.goods_price}</span>&nbsp;&nbsp;&nbsp;</span><em style="color: skyblue;">降价通知&nbsp;&nbsp;&nbsp;</em><strong>累计评价&nbsp;200+</strong></p>
        <p class="quan">
            <i style="color: #666;">优惠券&nbsp;&nbsp;&nbsp;</i><span style="color: red;">满2800减150</span><span style="color: red;">满2200减80</span><span style="color: red;">满1200减30</span>
            <em style="color: #666;">更多>></em>
        </p>
    </div>
    <div id="peiSongZhi" class="clear_fix">
        <a style="color: #666" class="fl">配&ensp;&nbsp;送&ensp;&nbsp;至&nbsp;</a>
        <a style="border:1px solid #CECBCE" class="fl">安徽合肥市包河区包公街道 ﹀</a>
        <a class="fl">&nbsp;有货&nbsp;&nbsp;</a>
        <a class="fl">&nbsp;免运费</a>
    </div>
    <div  class="shouhoufahuo">
        由<span style="color: #DF3033">墨者善石珠宝旗舰店</span>负责发货, 并提供售后服务. 今日17:00前完成下单,预计1月8日02:00前发货,4月10日24:00前送达
    </div>
    <div class="fuwuzhichi ">
        <span style="color: #666;">服&nbsp;务&nbsp;支&nbsp;持</span>
        <img src="../images/fangxingou .png" alt="">
        <strong>极速审核</strong>
    </div>
    <p class="shandiantuikuan"><span>闪电退款&nbsp;&nbsp;</span><span>运费险&nbsp;&nbsp;</span><span>材质优品保障&nbsp;&nbsp;</span><span>自提&nbsp;&nbsp;</span></p>
    <div class="xuanzequanhao ">
        <span class="fl">选&nbsp;择&nbsp;圈&nbsp;号</span>
        <div class="xuanxiang fl">
            <img src="../images/stu1.png" alt="" style="display: inline-block;" >
            <span>黄金戒指女款</span>
        </div>
        <div class="xuanxiang fl">
            <img src="../images/stu2.png" alt="" style="display: inline-block;" >
            <span>黄金戒指女款</span>
        </div>
        <div class="xuanxiang fl">
            <img src="../images/stu3.png" alt="" style="display: inline-block;" >
            <span>黄金戒指女款</span>
        </div>
    </div>
    <div class="baitiaofenqi clear_fix">
        <span class="fl">白&nbsp;条&nbsp;分&nbsp;期</span>
        <div class="xuanxiang fl">
           ￥777.49*3期
        </div>
        <div class="xuanxiang fl">
            ￥777.49*3期
         </div>
         <div class="xuanxiang fl">
            ￥777.49*3期
         </div>
    </div>
    <div class="clear_fix">
        <div class="number fl">
            <div class="num fl" >1</div>
            <div class="jia fl">+</div>
            <div class="jian fl">-</div>
        </div>
        <button class="add-cart1 fl">
        <a href='./cart.html'>加入购物车</a>
       
        </button>
    </div>
    <p class="tishi">温馨提示&nbsp;&nbsp;&nbsp;&nbsp;*支持7天无理由退货（定制类不支持）</p>
</div>
<img src="../images/youce.png" class='fr'
alt="">
${data.goods_introduce}
    `;
    xiangqing1.innerHTML = str;
    // Enlarge.prototype.tab();
    // 放大镜效果:
    function Enlarge(classname) {
      this.container = document.querySelector("." + classname);
      this.middleBox = this.container.querySelector(".middle");
      this.shade = this.container.querySelector(".middle .shade");
      this.bigBox = this.container.querySelector(".big");
      this.smallImgs = this.container.querySelectorAll(".small img");
      this.middleImg = this.container.querySelector(".middle>img");
      // 绑定事件
      this.init();
    }
    // 绑定事件的方法
    Enlarge.prototype.init = function () {
      // tab切换
      for (let i = 0; i < this.smallImgs.length; i++) {
        this.smallImgs[i].onmouseenter = () => {
          // tab交给另一个方法去做
          this.tab(i);
        };
      }
      // 鼠标移入
      this.middleBox.onmouseenter = () => {
        // 遮罩和大盒子显示
        this.shade.style.display = "block";
        this.bigBox.style.display = "block";
        // 中等盒子的移动事件
        this.middleBox.onmousemove = (e) => {
          var e = e || window.event;
          // 获取光标在浏览器中的位置
          var x = e.pageX;
          var y = e.pageY;
          // 计算遮罩的left和top
          // console.log(this.middleBox.offsetLeft);
          var left = x - this.shade.offsetWidth / 2 - this.middleBox.offsetLeft;
          var top = y - this.shade.offsetHeight / 2 - this.middleBox.offsetTop;
          // console.log(left, top);
          // 限制left和top
          if (left <= 0) {
            left = 0;
          }
          if (top <= 0) {
            top = 0;
          }
          if (left >= this.middleBox.clientWidth - this.shade.offsetWidth) {
            left = this.middleBox.clientWidth - this.shade.offsetWidth;
          }
          if (top >= this.middleBox.clientHeight - this.shade.offsetHeight) {
            top = this.middleBox.clientHeight - this.shade.offsetHeight;
          }
          // 将计算好的left和top设置给遮罩的left和top
          this.shade.style.left = left + "px";
          this.shade.style.top = top + "px";
          // 计算大图移动的距离
          this.bigImgMove(left, top);
        };
      };
      // 鼠标移出
      this.middleBox.onmouseleave = () => {
        this.shade.style.display = "none";
        this.bigBox.style.display = "none";
      };
    };
    // 大图移动的方法
    Enlarge.prototype.bigImgMove = function (left, top) {
      // 比例：遮罩在中图上移动的距离/中图的大小  = 大图移动的距离/大图的大小
      // 获取大图的大小
      var size = this.getStyle(this.bigBox, "background-size");
      // console.log(size);
      // 从size中分解出宽和高
      var arr = size.split(" ");
      var width = parseFloat(arr[0]);
      var height = parseFloat(arr[1]);
      // 计算需要移动的距离
      var bigLeft = (left / this.middleBox.clientWidth) * width;
      var bigTop = (top / this.middleBox.clientHeight) * height;
      // 将计算好的left和top设置给大盒子
      this.bigBox.style.backgroundPosition = `-${bigLeft}px -${bigTop}px`;
    };
    // 获取样式的方法
    Enlarge.prototype.getStyle = function (ele, attr) {
      if (window.getComputedStyle) {
        return window.getComputedStyle(ele)[attr];
      } else {
        return ele.currentStyle[attr];
      }
    };
    // tab切换的方法
    Enlarge.prototype.tab = function (index) {
      // 去掉所有小图的active 类名
      for (var i = 0; i < this.smallImgs.length; i++) {
        this.smallImgs[i].className = "";
      }
      // 给当前的加active
      this.smallImgs[index].className = "active";
      // 换图
      // 获取到小图的src，通过小图的src组合中图的src，组合大图的url
      var smallImgPath = this.smallImgs[index].getAttribute("src");
      // console.log(smallImgPath);
      // . 最后一次出现的下标
      var lastIndex = smallImgPath.lastIndexOf(".");
      // console.log(lastIndex);
      // 截取数字+后缀
      var suffix = smallImgPath.slice(lastIndex - 1);
      // console.log(suffix);
      // 组合中图的src   ./images/ltu1.png
      var middleImgPath = `${data.goods_small_logo}`;
      // console.log(middleImgPath);
      // 更换中图的src
      this.middleImg.setAttribute("src", middleImgPath);
      // 组合大图的url  ./images/xltu1.png
      var bigImgUrl = `${data.goods_big_logo}`;
      // console.log(bigImgUrl);
      // 给大盒子更换背景图
      this.bigBox.style.backgroundImage = `url(${bigImgUrl})`;
    };
    var en = new Enlarge("enlarge");
    $(".small img").trigger("mouseenter");
  })();
} else {
  alert("非法进入");
  // 重新跳回列表页
  location = "./list.html";
}

// 给大盒子添加点击事件 (点击加入购物车，就会向localStorage中的cartList添加数据)
xiangqing1.onclick = function (e) {
  // console.log(data);
  var target = e.target || e.srcElement;
  if (target.innerHTML == "加入购物车") {
    var cartList = localStorage.getItem("cartList") || [];
    // cartList = JSON.parse(cartList).forEach((el) => {
    //   delete el.goods_introduce;
    // });
    // console.log(JSON.parse(cartList));
    if (cartList.length > 0) {
      cartList = eval("(" + cartList + ")");
      var bool = false;
      cartList.forEach((item) => {
        if (item.goods_id == data.goods_id) {
          item.cart_number++;
          bool = true;
          localStorage.setItem("cartList", JSON.stringify(cartList));
        }
      });

      if (!bool) {
        data.cart_number = 1;
        cartList.push(data);
        localStorage.setItem("cartList", JSON.stringify(cartList));
      }
    } else {
      data.cart_number = 1;
      cartList.push(data);
      localStorage.setItem("cartList", JSON.stringify(cartList));
    }
  } else {
    console.log(1);
  }
};
